<script setup>
import * as echarts from "echarts";
const props = defineProps({
  // 配置项
  option: {
    type: Object,
    default: {},
  },
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "100%",
  },
  loading: {
    type: Boolean,
    default: false,
  },
});
const chartRef = ref(null);
const alarmNumEcharts = shallowRef();
// 初始化
const initEcharts = () => {
  const chartDom = unref(chartRef);
  alarmNumEcharts.value = echarts.init(chartDom);

  alarmNumEcharts.value.showLoading(props.loading); // loading
  // 若图表需要点击事件做些其他功能，在初始化示例时注册图表的点击事件
  if (props.isClick) {
    alarmNumEcharts.value.on("click", (params) => {
      emits("callbackFun", params);
    });
  }
  // if (props.option) {
  //   clearInterval(timer.value);
  alarmNumEcharts.value.setOption(props.option, true);
  //   lunboEcharts(alarmNumEcharts.value, props.option.series[0].data.length);
  // }
  window.addEventListener("resize", chartsResize);
};

//轮播tootip
const timer = ref(null);
function lunboEcharts(echartsId, dataLen, currentIndex = -1) {
  timer.value = setInterval(() => {
    echartsId.dispatchAction({
      type: "downplay",
      seriesIndex: 0,
      dataIndex: currentIndex,
    });
    currentIndex = (currentIndex + 1) % dataLen;
    echartsId.dispatchAction({
      type: "highlight",
      seriesIndex: 0,
      dataIndex: currentIndex,
    });
    echartsId.dispatchAction({
      type: "showTip",
      seriesIndex: 0,
      dataIndex: currentIndex,
    });
  }, 3000);
}

const chartsResize = () => {
  alarmNumEcharts.value && alarmNumEcharts.value.resize();
};

onBeforeUnmount(() => {
  window.removeEventListener("resize", chartsResize);
  alarmNumEcharts.value = null;
});

watch(
  () => props.option,
  (val) => {
    nextTick(() => {
      initEcharts();
    });
  },
  {
    deep: true,
    immediate: true,
  }
);
</script>

<template>
  <div
    class="echarts"
    ref="chartRef"
    :style="{
      width: props.width,
      height: props.height,
    }"
  ></div>
</template>
<style scoped lang="scss">
.echarts {
  width: 100%;
  height: 100%;
}
</style>
